package ru.nnstu.medialib.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import java.sql.ResultSet;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

@SuppressWarnings("deprecation")
public class HibernateUtil {

	public static final SessionFactory SESSION_FACTORY;
	public static final ThreadLocal SESSION = new ThreadLocal();
	
	static Connection conn;
	static Statement st;

	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			SESSION_FACTORY = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			// Make sure you log the exception, as it might be swallowed
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static Session getSession() throws HibernateException {
		Session s = (Session) SESSION.get();
		// Open a new Session, if this thread has none yet
		if (s == null) {
			s = SESSION_FACTORY.openSession();
			// Store it in the ThreadLocal variable
			SESSION.set(s);
		}
		return s;
	}

	public static void closeSession() throws HibernateException {
		Session s = (Session) SESSION.get();
		if (s != null)
			s.close();
		SESSION.set(null);
	}


	public static void setup(String sql) {
		try {
			// Step 1: Load the JDBC driver.
			Class.forName("org.postgresql.Driver");
			System.err.println("Driver Loaded.");
			// Step 2: Establish the connection to the database.
			String url = "jdbc:postgresql://localhost:5432/media";
			conn = DriverManager.getConnection(url, "postgres", "admin");
			System.err.println("Got Connection.");
			st = conn.createStatement();
			st.executeUpdate(sql);
		} catch (Exception e) {
			System.err.println("Table loaded.");
			e.printStackTrace();
			System.exit(0);
		}
	}

	public static ResultSet getResultSet(String sql) throws Exception {
		ResultSet rs = st.executeQuery(sql);
		return rs;

	}
}